/*
 *    Copyright (c) 2018-2025, 云集汇通 All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * Redistributions of source code must retain the above copyright notice,
 * this list of conditions and the following disclaimer.
 * Redistributions in binary form must reproduce the above copyright
 * notice, this list of conditions and the following disclaimer in the
 * documentation and/or other materials provided with the distribution.
 * Neither the name of the yunjihuitong.com developer nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 */

package com.yjht.common.handler;

import com.yjht.common.exception.LocalException;
import com.yjht.common.utils.R;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authz.AuthorizationException;
import org.springframework.context.MessageSource;
import org.springframework.context.NoSuchMessageException;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.Locale;

/**
 * 异常处理器
 *
 * @author Mark wangiegie@gmail.com
 * @since 1.0.0 2016-10-27
 */
@Slf4j
@AllArgsConstructor
@RestControllerAdvice
public class LimsExceptionHandler {
    private final MessageSource messageSource;

    /**
     * 处理自定义异常
     *
     * @param e
     * @return
     */
    @ExceptionHandler(LocalException.class)
    public R handleLocalException(LocalException e) {
        Locale locale = LocaleContextHolder.getLocale();
        String resultMsg;
        try {
            resultMsg = messageSource.getMessage(e.getMsg(), e.getParams(), locale);
        } catch (NoSuchMessageException ex) {
            resultMsg = "异常没有国际化定义";
        }
        R r = new R();
        r.put("code", e.getCode());
        r.put("msg", resultMsg);
        return r;
    }

    @ExceptionHandler(DuplicateKeyException.class)
    public R handleDuplicateKeyException(DuplicateKeyException e) {
        log.error(e.getMessage(), e);
        return R.error("数据库中已存在该记录");
    }

    @ExceptionHandler(AuthorizationException.class)
    public R handleAuthorizationException(AuthorizationException e) {
        log.error(e.getMessage(), e);
        return R.error("没有权限，请联系管理员授权");
    }

    @ExceptionHandler(Exception.class)
    public R handleException(Exception e) {
        log.error(e.getMessage(), e);
        return R.error();
    }
}
